#include "sentry.h"

Sentry::Sentry(QWidget *parent, Qt::WFlags flags)
	: QMainWindow(parent, flags)
{
	ui.setupUi(this);

	AutoOn = false;
	ManualOn = false;
	IsConnected = false;
	FoundCams = false;
	Xas = 90;
	Yas = 90;

	CurrentCom = "COM8";
	QString FoundCom;

	Comm = new Communicator;

	thread = new QThread;

	Comm->CommDone = CreateEvent(  NULL,      TRUE,    FALSE,  LPCWSTR("CommDone")); 
	Comm->NewData = CreateEvent(  NULL,      TRUE,    FALSE,  LPCWSTR("NewData")); 

	Comm->moveToThread(thread);

	//set slider ranges, disable by default until calibrate button is hit
	ui.HueLow->setRange(0, 179);
	ui.HueHigh->setRange(0, 179);
	ui.SatLow->setRange(0, 255);
	ui.SatHigh->setRange(0, 255);
	ui.ValLow->setRange(0, 255);
	ui.ValHigh->setRange(0, 255);

	//disable the sliders and reset buttons by default
	ui.HueLow->setEnabled(false);
	ui.HueHigh->setEnabled(false);
	ui.SatLow->setEnabled(false);
	ui.SatHigh->setEnabled(false);
	ui.ValLow->setEnabled(false);
	ui.ValHigh->setEnabled(false);
	ui.ResetHighButton->setEnabled(false);
	ui.ResetLowButton->setEnabled(false);
	ui.LockHigherButton->setEnabled(false);
	ui.LockLowerButton->setEnabled(false);

	//set slider stepsize to 1, by default stepsize is 10 (clicking on the sliderbar)
	ui.HueLow->setPageStep(1);
	ui.HueHigh->setPageStep(1);
	ui.SatLow->setPageStep(1);
	ui.SatHigh->setPageStep(1);
	ui.ValLow->setPageStep(1);
	ui.ValHigh->setPageStep(1);

	//disable the textboxes as well so they can't be edited through text edit
	ui.HueLowVal->setEnabled(false);
	ui.HueHighVal->setEnabled(false);
	ui.SatLowVal->setEnabled(false);
	ui.SatHighVal->setEnabled(false);
	ui.ValLowVal->setEnabled(false);
	ui.ValHighVal->setEnabled(false);

	//Com port data structure for storing detected com port
	COMMCONFIG ccfg;

	//Search for com ports, if a comport is found then store it as an item in the combobox.
	//The item is an device id that is used in the setup function to setup an connection. 
	for (int i = 0; i < 20; i++)
	{
		std::ostringstream oss;
		oss << "COM" << i;
		ccfg.dwSize = sizeof COMMCONFIG;
		DWORD siz = sizeof COMMCONFIG;
		std::string comstring = oss.str();

		//Get comport config, the comport than named bij the comstring. The function retuns true if the configuration info is successfully retrieved.
		//This means that we have an valid comport.
		BOOL res = GetDefaultCommConfigA (comstring.c_str(), &ccfg, &siz);
		if (res){
			ui.ComComboBox->addItem("COM" + QString::number(i));
		};
	};

	// signals/slots mechanism in action
	connect(Comm, SIGNAL(error(QString)), this, SLOT(errorString(QString)));
	connect(thread, SIGNAL(started()), Comm, SLOT(run()));
	connect(Comm, SIGNAL(Disconnect()), thread, SLOT(quit()));
	connect(Comm, SIGNAL(Disconnect()), Comm, SLOT(deleteLater()));
	connect(thread, SIGNAL(Disconnect()), thread, SLOT(deleteLater()));
	connect(ui.GetImageButton, SIGNAL( clicked() ), this, SLOT( GetImage() ) ); 
	connect(ui.QuitModeButton, SIGNAL( clicked() ), this, SLOT( QuitMode() ) ); 
	connect(ui.ConnectButton, SIGNAL( clicked() ), this, SLOT( Connect() ) ); 
	connect(ui.DisconnectButton, SIGNAL( clicked() ), this, SLOT( Disconnect() ) ); 
	connect(ui.AutoDynamicButton, SIGNAL( clicked() ), this, SLOT( TrackingDynamic() ) ); 
	connect(ui.AutoButton, SIGNAL( clicked() ), this, SLOT( GetImage() ) ); 
	connect(ui.ManualButton, SIGNAL( clicked() ), this, SLOT( Manual() ) );
	connect(ui.UpButton, SIGNAL( pressed()  ), this, SLOT( Up() ) );
	connect(ui.RightButton, SIGNAL( pressed() ), this, SLOT( Right() ) );
	connect(ui.DownButton, SIGNAL( pressed() ), this, SLOT( Down() ) );
	connect(ui.LeftButton, SIGNAL( pressed() ), this, SLOT( Left() ) );
	connect(ui.FireButton, SIGNAL( pressed() ), this, SLOT( Fire() ) );
	connect(ui.ClearLogButton, SIGNAL( pressed() ), this, SLOT( ClearLog() ) );
	connect(ui.SaveLogButton, SIGNAL( pressed() ), this, SLOT( SaveLog() ) );
	connect(ui.LoadLogButton, SIGNAL( pressed() ), this, SLOT( LoadLog() ) );

	connect(ui.UpButton, SIGNAL( released()  ), this, SLOT( SetButton() ) );
	connect(ui.RightButton, SIGNAL( released() ), this, SLOT( SetButton() ) );
	connect(ui.DownButton, SIGNAL( released() ), this, SLOT( SetButton() ) );
	connect(ui.LeftButton, SIGNAL( released() ), this, SLOT( SetButton() ) );
	connect(ui.FireButton, SIGNAL( released() ), this, SLOT( SetButton() ) );

	connect(ui.ComComboBox, SIGNAL(activated(int)), this, SLOT( UpdateCom() ) );

	connect(ui.CalibButton, SIGNAL( clicked() ), this, SLOT( Calibrate() ) );
	connect(ui.HueLow, SIGNAL( valueChanged(int) ), this, SLOT (SetHueLow(int) ) );
	connect(ui.HueHigh, SIGNAL ( valueChanged(int) ), this, SLOT (SetHueHigh(int) ) );
	connect(ui.SatLow, SIGNAL ( valueChanged(int) ), this, SLOT (SetSatLow(int) ) );
	connect(ui.SatHigh, SIGNAL ( valueChanged(int) ), this, SLOT (SetSatHigh(int) ) );
	connect(ui.ValLow, SIGNAL ( valueChanged(int) ), this, SLOT (SetValLow(int) ) );
	connect(ui.ValHigh, SIGNAL ( valueChanged(int) ), this, SLOT (SetValHigh(int) ) );
	connect(ui.ResetLowButton, SIGNAL (clicked() ), this, SLOT ( ResetLowVals() ) );
	connect(ui.ResetHighButton, SIGNAL (clicked() ), this, SLOT ( ResetHighVals() ) );
	connect(ui.LockLowerButton, SIGNAL (clicked() ), this, SLOT ( LockLowerVals() ) );
	connect(ui.LockHigherButton, SIGNAL (clicked() ), this, SLOT ( LockHigherVals() ) );

	connect(ui.MotionButton, SIGNAL ( clicked() ), this, SLOT ( Beweging_detector_caller() ) );

	ui.ImageView->setPixmap(QPixmap("logo.jpg")); 
	ui.OfflineLed->setProperty("value", QVariant(true));

	blob.LastTransX = 0;
	blob.LastMassCol = 0;
	blob.LastMassRow = 0;
	blob.LastTransY = 0;

	Mat CheckFrame;
	thread->quit();
	Cam.open(1);

	Cam >> CheckFrame;

	blob.XCentre = CheckFrame.cols / 2;
	blob.YCentre = CheckFrame.rows / 2;

	ui.radioBlue->setChecked(true);
	ui.radioNormal->setChecked(true);
	ui.UpButton->setEnabled(false);
	ui.RightButton->setEnabled(false);
	ui.DownButton->setEnabled(false);
	ui.LeftButton->setEnabled(false);
	ui.FireButton->setEnabled(false);

	//Check if a adrduino is connected. If so then setup up the connection and set the uplink light on.
	if(Comm->Setup(CurrentCom) == 0){
		ui.UpLinkLed->setProperty("value", QVariant(true));
		ui.LogView->append("[" + Time.currentDateTime().toString ("hh:mm:ss.zzz") + "] " + "Uplink established");
		ui.ConnectButton->setEnabled(false);
		ui.DisconnectButton->setEnabled(true);
		QCoreApplication::processEvents();
		UpLink = true;
	}
	else{
		ui.UpLinkLed->setProperty("value", QVariant(false));
		ui.LogView->append("[" + Time.currentDateTime().toString ("hh:mm:ss.zzz") + "] " + "Uplink failed");
		UpLink = false;
		ui.AutoButton->setEnabled(false);
		ui.ManualButton->setEnabled(false);
		ui.AutoDynamicButton->setEnabled(false);
		ui.ConnectButton->setEnabled(true);
		ui.DisconnectButton->setEnabled(false);
		QCoreApplication::processEvents();
	};
	thread->start();
	ui.LogView->append("[" + Time.currentDateTime().toString ("hh:mm:ss.zzz") + "] " + "System ready");
	QCoreApplication::processEvents();
}

Sentry::~Sentry(){
	AutoOn = false;
	blob.Cam.~VideoCapture(); 
	QCoreApplication::processEvents();
	QCoreApplication::quit();
};

void Sentry::GetImage(){
	if(UpLink){
		AutoOn = true;
		ui.LogView->append("[" + Time.currentDateTime().toString ("hh:mm:ss.zzz") + "] " + "Static tracking activated");
		ui.OfflineLed->setProperty("value", QVariant(false));
		ui.ManualLed->setProperty("value", QVariant(false));
		ui.InitLed->setProperty("value", QVariant(true));
		ui.DataView->setText("Auto mode activated");
		ui.AutoButton->setEnabled(false);
		ui.AutoDynamicButton->setEnabled(true);
		ui.ManualButton->setEnabled(true);
		ui.UpButton->setEnabled(false);
		ui.RightButton->setEnabled(false);
		ui.DownButton->setEnabled(false);
		ui.LeftButton->setEnabled(false);
		ui.FireButton->setEnabled(false);
		QCoreApplication::processEvents();
		thread->start();
		Sleep(5000);
		ui.InitLed->setProperty("value", QVariant(false));
		ui.AutoLed->setProperty("value", QVariant(true));
		cvWaitKey(1);
		QCoreApplication::processEvents();

		while(AutoOn){
			cvWaitKey(1);
			QCoreApplication::processEvents();

			if(ui.radioNormal->isChecked()){
				ui.DataView->setText("Showing result image");

				if(ui.radioBlue->isChecked()){
					blob.LoadLiveFeed(Cam,1);
					ui.HueLow->setValue(blob.Blue.HLower);    //Kan dit niet in de calibrate functie aangezien calbireren alleen in de calibrate functie mag.
					ui.SatLow->setValue(blob.Blue.SLower);
					ui.ValLow->setValue(blob.Blue.VLower);
					ui.HueHigh->setValue(blob.Blue.HUpper);
					ui.SatHigh->setValue(blob.Blue.SUpper);
					ui.ValHigh->setValue(blob.Blue.VUpper);
					ui.HueLowVal->append(QString::number(blob.Blue.HLower));
					ui.SatLowVal->append(QString::number(blob.Blue.SLower));
					ui.ValLowVal->append(QString::number(blob.Blue.VLower));
					ui.HueHighVal->append(QString::number(blob.Blue.HUpper));
					ui.SatHighVal->append(QString::number(blob.Blue.SUpper));
					ui.ValHighVal->append(QString::number(blob.Blue.VUpper));
				}
				else if(ui.radioYellow->isChecked()){
					blob.LoadLiveFeed(Cam,2);
					ui.HueLow->setValue(blob.Yellow.HLower);
					ui.SatLow->setValue(blob.Yellow.SLower);
					ui.ValLow->setValue(blob.Yellow.VLower);
					ui.HueHigh->setValue(blob.Yellow.HUpper);
					ui.SatHigh->setValue(blob.Yellow.SUpper);
					ui.ValHigh->setValue(blob.Yellow.VUpper);
					ui.HueLowVal->append(QString::number(blob.Yellow.HLower));
					ui.SatLowVal->append(QString::number(blob.Yellow.SLower));
					ui.ValLowVal->append(QString::number(blob.Yellow.VLower));
					ui.HueHighVal->append(QString::number(blob.Yellow.HUpper));
					ui.SatHighVal->append(QString::number(blob.Yellow.SUpper));
					ui.ValHighVal->append(QString::number(blob.Yellow.VUpper));
				}
				else if(ui.radioGreen->isChecked()){
					blob.LoadLiveFeed(Cam,3);
					ui.HueLow->setValue(blob.Green.HLower);
					ui.SatLow->setValue(blob.Green.SLower);
					ui.ValLow->setValue(blob.Green.VLower);
					ui.HueHigh->setValue(blob.Green.HUpper);
					ui.SatHigh->setValue(blob.Green.SUpper);
					ui.ValHigh->setValue(blob.Green.VUpper);
					ui.HueLowVal->append(QString::number(blob.Green.HLower));
					ui.SatLowVal->append(QString::number(blob.Green.SLower));
					ui.ValLowVal->append(QString::number(blob.Green.VLower));
					ui.HueHighVal->append(QString::number(blob.Green.HUpper));
					ui.SatHighVal->append(QString::number(blob.Green.SUpper));
					ui.ValHighVal->append(QString::number(blob.Green.VUpper));
				}
				else if(ui.radioRed->isChecked()){
					blob.LoadLiveFeed(Cam,4);
					ui.HueLow->setValue(blob.Red.HLower);
					ui.SatLow->setValue(blob.Red.SLower);
					ui.ValLow->setValue(blob.Red.VLower);
					ui.HueHigh->setValue(blob.Red.HUpper);
					ui.SatHigh->setValue(blob.Red.SUpper);
					ui.ValHigh->setValue(blob.Red.VUpper);
					ui.HueLowVal->append(QString::number(blob.Red.HLower));
					ui.SatLowVal->append(QString::number(blob.Red.SLower));
					ui.ValLowVal->append(QString::number(blob.Red.VLower));
					ui.HueHighVal->append(QString::number(blob.Red.HUpper));
					ui.SatHighVal->append(QString::number(blob.Red.SUpper));
					ui.ValHighVal->append(QString::number(blob.Red.VUpper));
				}
				else{
					blob.LoadLiveFeed(Cam,0);
				};
				blob.Image_Scan();

				cvtColor(blob.Image, blob.QTImage, CV_BGR2RGB);
				qimage = QImage(blob.QTImage.data, blob.QTImage.cols, blob.QTImage.rows, blob.QTImage.cols*3, QImage::Format_RGB888);
				pixmap = QPixmap::fromImage(qimage);
				ui.ImageView->setPixmap(pixmap); 
				ui.ImageView->adjustSize();

				if ((blob.LastMassCol != blob.LastTransX) || (blob.LastMassRow != blob.LastTransY))
				{
					ui.TXLed->setProperty("value", QVariant(true));
					QCoreApplication::processEvents();
					ui.TXLed->setProperty("value", QVariant(false));
					QCoreApplication::processEvents();
					OutputUnit.ConvertToDegrees(blob.LastMassRow, blob.LastMassCol, blob.Frame.rows, blob.Frame.cols);
					Comm->X = OutputUnit.OutputX;
					Comm->Y = OutputUnit.OutputY;

					//Display the data that has been put in the send struct.
					ui.CommView->append( "==========================");
					ui.CommView->append( "X value com: " + QString::number(Comm->X) );
					ui.CommView->append( "y value com: " + QString::number(Comm->Y) );
					QCoreApplication::processEvents();
					//New data is avalible, set NewData event.
					SetEvent(Comm->NewData);

					WaitForSingleObject(Comm->CommDone, INFINITE);

					//Display the data that has been recieved.
					ui.CommView->append( "X return value: " + QString::number(Comm->RecvData.Struc.AngleX) );	
					ui.CommView->append( "Y return value: " + QString::number(Comm->RecvData.Struc.AngleY) );	
					blob.LastTransX = blob.LastMassCol;
					blob.LastTransY = blob.LastMassRow;
					ResetEvent(Comm->CommDone);
					//ResetEvent(Comm->NewData);

					ui.RXLed->setProperty("value", QVariant(true));
					QCoreApplication::processEvents();
					ui.RXLed->setProperty("value", QVariant(false));
					QCoreApplication::processEvents();
				};

				cvWaitKey(1);
				QCoreApplication::processEvents();
			}
			else if(ui.radioScratch->isChecked()){
				ui.DataView->setText("Showing scratch image");
				if(ui.radioBlue->isChecked()){
					blob.LoadLiveFeed(Cam,1);
				}
				else if(ui.radioYellow->isChecked()){
					blob.LoadLiveFeed(Cam,2);
				}
				else if(ui.radioGreen->isChecked()){
					blob.LoadLiveFeed(Cam,3);
				}
				else if(ui.radioRed->isChecked()){
					blob.LoadLiveFeed(Cam,4);
				}
				else{
					blob.LoadLiveFeed(Cam,0);
				};
				blob.Image_Scan();

				qimage = QImage(blob.Scratch.data, blob.Scratch.cols, blob.Scratch.rows, blob.Scratch.cols, QImage::Format_Indexed8);
				pixmap = QPixmap::fromImage(qimage);
				ui.ImageView->setPixmap(pixmap); 
				ui.ImageView->adjustSize();

				if ((blob.LastMassCol != blob.LastTransX) || (blob.LastMassRow != blob.LastTransY))
				{
					ui.TXLed->setProperty("value", QVariant(true));
					QCoreApplication::processEvents();
					ui.TXLed->setProperty("value", QVariant(false));
					QCoreApplication::processEvents();
					OutputUnit.ConvertToDegrees(blob.LastMassRow, blob.LastMassCol, blob.Frame.rows, blob.Frame.cols);
					Comm->X = OutputUnit.OutputX;
					Comm->Y = OutputUnit.OutputY;

					//Display the data that has been put in the send struct.
					ui.CommView->append( "==========================");
					ui.CommView->append( "X value com: " + QString::number(Comm->X) );
					ui.CommView->append( "Y value com: " + QString::number(Comm->Y) );

					//New data is avalible, set NewData event.
					SetEvent(Comm->NewData);

					WaitForSingleObject(Comm->CommDone, INFINITE);

					//Display the data that has been recieved.
					ui.CommView->append( "X return value: " + QString::number(Comm->RecvData.Struc.AngleX) );	
					ui.CommView->append( "Y return value: " + QString::number(Comm->RecvData.Struc.AngleY) );	
					blob.LastTransX = blob.LastMassCol;
					blob.LastTransY = blob.LastMassRow;
					ResetEvent(Comm->CommDone);
					//ResetEvent(Comm->NewData);

					ui.RXLed->setProperty("value", QVariant(true));
					QCoreApplication::processEvents();
					ui.RXLed->setProperty("value", QVariant(false));
					QCoreApplication::processEvents();
				};
				cvWaitKey(1);
				QCoreApplication::processEvents();
			}
			else if(ui.radioThreshold->isChecked()){
				ui.DataView->setText("Showing threshold image");
				if(ui.radioBlue->isChecked()){
					blob.LoadLiveFeed(Cam,1);
				}
				else if(ui.radioYellow->isChecked()){
					blob.LoadLiveFeed(Cam,2);
				}
				else if(ui.radioGreen->isChecked()){
					blob.LoadLiveFeed(Cam,3);
				}
				else if(ui.radioRed->isChecked()){
					blob.LoadLiveFeed(Cam,4);
				}
				else{
					blob.LoadLiveFeed(Cam,0);
				};
				blob.Image_Scan();

				qimage = QImage(blob.WorkImage.data, blob.WorkImage.cols, blob.WorkImage.rows, blob.WorkImage.cols, QImage::Format_Indexed8);
				pixmap = QPixmap::fromImage(qimage);
				ui.ImageView->setPixmap(pixmap); 
				ui.ImageView->adjustSize();

				if ((blob.LastMassCol != blob.LastTransX) || (blob.LastMassRow != blob.LastTransY))
				{
					ui.TXLed->setProperty("value", QVariant(true));
					QCoreApplication::processEvents();
					ui.TXLed->setProperty("value", QVariant(false));
					QCoreApplication::processEvents();
					OutputUnit.ConvertToDegrees(blob.LastMassRow, blob.LastMassCol, blob.Frame.rows, blob.Frame.cols);
					Comm->X = OutputUnit.OutputX;
					Comm->Y = OutputUnit.OutputY;

					//Display the data that has been put in the send struct.
					ui.CommView->append( "==========================");
					ui.CommView->append( "X value com: " + QString::number(Comm->X) );
					ui.CommView->append( "Y value com: " + QString::number(Comm->Y) );

					//New data is avalible, set NewData event.
					SetEvent(Comm->NewData);

					WaitForSingleObject(Comm->CommDone, INFINITE);

					//Display the data that has been recieved.
					ui.CommView->append( "X return value: " + QString::number(Comm->RecvData.Struc.AngleX) );	
					ui.CommView->append( "Y return value: " + QString::number(Comm->RecvData.Struc.AngleY) );	
					blob.LastTransX = blob.LastMassCol;
					blob.LastTransY = blob.LastMassRow;
					ResetEvent(Comm->CommDone);
					//ResetEvent(Comm->NewData);

					ui.RXLed->setProperty("value", QVariant(true));
					QCoreApplication::processEvents();
					ui.RXLed->setProperty("value", QVariant(false));
					QCoreApplication::processEvents();
				};
				cvWaitKey(1);
				QCoreApplication::processEvents();
			}else{
				ui.DataView->setText("No image type loaded");
				cvWaitKey(1);
				QCoreApplication::processEvents();
			};
			cvWaitKey(1);
			QCoreApplication::processEvents();
		};
	}
	else{
		ui.LogView->append("[" + Time.currentDateTime().toString ("hh:mm:ss.zzz") + "] " + "Cannot execute static tracking mode, uplink not establisched");
	};
};

void Sentry::TrackingDynamic(){
	if(UpLink){
		AutoOn = true;
		int X = 90;
		int Y = 90;
		ui.OfflineLed->setProperty("value", QVariant(false));
		ui.ManualLed->setProperty("value", QVariant(false));
		ui.InitLed->setProperty("value", QVariant(true));
		ui.DataView->setText("Auto mode activated");
		ui.LogView->append("[" + Time.currentDateTime().toString ("hh:mm:ss.zzz") + "] " + "Dynamic tracking activated");
		ui.AutoButton->setEnabled(true);
		ui.AutoDynamicButton->setEnabled(false);
		ui.ManualButton->setEnabled(true);
		ui.UpButton->setEnabled(false);
		ui.RightButton->setEnabled(false);
		ui.DownButton->setEnabled(false);
		ui.LeftButton->setEnabled(false);
		ui.FireButton->setEnabled(false);
		QCoreApplication::processEvents();
		thread->start();
		Sleep(5000);
		ui.InitLed->setProperty("value", QVariant(false));
		ui.AutoLed->setProperty("value", QVariant(true));
		cvWaitKey(1);
		ui.CommView->append( "Centering gun..." );
		QCoreApplication::processEvents();

		//Center gun.
		Comm->X = X;
		Comm->Y = Y;

		//New data is avalible, set NewData event.
		SetEvent(Comm->NewData);

		WaitForSingleObject(Comm->CommDone, INFINITE);

		//Display the data that has been recieved.
		ResetEvent(Comm->CommDone);
		ui.CommView->append( "Gun centert" );
		QCoreApplication::processEvents();

		while(AutoOn){
			cvWaitKey(1);
			QCoreApplication::processEvents();

			if(ui.radioNormal->isChecked()){
				ui.DataView->setText("Showing result image");

				if(ui.radioBlue->isChecked()){
					blob.LoadLiveFeed(Cam,1);
				}
				else if(ui.radioYellow->isChecked()){
					blob.LoadLiveFeed(Cam,2);
				}
				else if(ui.radioGreen->isChecked()){
					blob.LoadLiveFeed(Cam,3);
				}
				else if(ui.radioRed->isChecked()){
					blob.LoadLiveFeed(Cam,4);
				}
				else{
					blob.LoadLiveFeed(Cam,0);
				};
				blob.Image_Scan();

				cvtColor(blob.Image, blob.QTImage, CV_BGR2RGB);
				qimage = QImage(blob.QTImage.data, blob.QTImage.cols, blob.QTImage.rows, blob.QTImage.cols*3, QImage::Format_RGB888);
				pixmap = QPixmap::fromImage(qimage);
				ui.ImageView->setPixmap(pixmap); 
				ui.ImageView->adjustSize();

				ui.TXLed->setProperty("value", QVariant(true));
				QCoreApplication::processEvents();
				ui.TXLed->setProperty("value", QVariant(false));
				QCoreApplication::processEvents();

				//Check X
				if((blob.LastMassCol) < ((blob.WorkImage.cols / 2) - 10)){
					X++;
					Comm->X = X;
					ui.CommView->append( "left" );
				}else if((blob.LastMassCol) > ((blob.WorkImage.cols / 2) + 10 )) {

					X--;
					Comm->X = X;
					ui.CommView->append( "right" );
				}else{
					ui.CommView->append( "On target" );
				};

				//Check Y
				if((blob.LastMassRow) < ((blob.WorkImage.rows / 2) - 5)){
					Y++;
					Comm->Y = Y;
					ui.CommView->append( "down" );
				}else if((blob.LastMassRow) > ((blob.WorkImage.rows / 2) + 5)){
					Y--;
					Comm->Y = Y;
					ui.CommView->append( "up" );
				};

				//New data is avalible, set NewData event.
				SetEvent(Comm->NewData);

				WaitForSingleObject(Comm->CommDone, INFINITE);

				blob.LastTransX = blob.LastMassCol;
				blob.LastTransY = blob.LastMassRow;
				ResetEvent(Comm->CommDone);
				//ui.CommView->append( "Gun centert" );

				//if (((Y-1) == -1) || ((Y+1) == 180) ||
				if ((X == 0) || (X == 180)){

					ui.CommView->append( "Target out of range, centering gun" );

					Y = 90;
					X = 90;

					//Center gun.
					Comm->X = X;
					Comm->Y = Y;

					//New data is avalible, set NewData event.
					SetEvent(Comm->NewData);

					WaitForSingleObject(Comm->CommDone, INFINITE);

					//Display the data that has been recieved.
					ResetEvent(Comm->CommDone);
					ui.CommView->append( "Gun centert" );
					QCoreApplication::processEvents();
				};
				//};

				ui.RXLed->setProperty("value", QVariant(true));
				QCoreApplication::processEvents();
				ui.RXLed->setProperty("value", QVariant(false));
				QCoreApplication::processEvents();

				cvWaitKey(1);
				QCoreApplication::processEvents();
				//Sleep(1000);
			}
			else if(ui.radioScratch->isChecked()){
				ui.DataView->setText("Showing scratch image");
				if(ui.radioBlue->isChecked()){
					blob.LoadLiveFeed(Cam,1);
				}
				else if(ui.radioYellow->isChecked()){
					blob.LoadLiveFeed(Cam,2);
				}
				else if(ui.radioGreen->isChecked()){
					blob.LoadLiveFeed(Cam,3);
				}
				else if(ui.radioRed->isChecked()){
					blob.LoadLiveFeed(Cam,4);
				}
				else{
					blob.LoadLiveFeed(Cam,0);
				};
				blob.Image_Scan();

				qimage = QImage(blob.Scratch.data, blob.Scratch.cols, blob.Scratch.rows, blob.Scratch.cols, QImage::Format_Indexed8);
				pixmap = QPixmap::fromImage(qimage);
				ui.ImageView->setPixmap(pixmap); 
				ui.ImageView->adjustSize();

				ui.TXLed->setProperty("value", QVariant(true));
				QCoreApplication::processEvents();
				ui.TXLed->setProperty("value", QVariant(false));
				QCoreApplication::processEvents();

				//Check X
				if((blob.LastMassCol) < ((blob.WorkImage.cols / 2) - 10)){
					X++;
					Comm->X = X;
					ui.CommView->append( "left" );
				}else if((blob.LastMassCol) > ((blob.WorkImage.cols / 2) + 10)) {

					X--;
					Comm->X = X;
					ui.CommView->append( "right" );
				}else{
					ui.CommView->append( "On target" );
				};

				//Check Y
				if((blob.LastMassRow) < ((blob.WorkImage.rows / 2) + 10)){
					Y++;
					Comm->Y = Y;
					ui.CommView->append( "down" );
				}else if((blob.LastMassRow) > ((blob.WorkImage.rows / 2) - 10)){
					Y--;
					Comm->Y = Y;
					ui.CommView->append( "up" );
				};


				//New data is avalible, set NewData event.
				SetEvent(Comm->NewData);

				WaitForSingleObject(Comm->CommDone, INFINITE);

				blob.LastTransX = blob.LastMassCol;
				blob.LastTransY = blob.LastMassRow;
				ResetEvent(Comm->CommDone);

				//if (((Y-1) == -1) || ((Y+1) == 180) || ((X-1) == -1) || ((X+1) == 180)){
				if ((X == 0) || (X == 180)){
					ui.CommView->append( "Target out of range, centering gun" );
					QCoreApplication::processEvents();
					Y = 90;
					X = 90;

					//Center gun.
					Comm->X = X;
					Comm->Y = Y;

					//New data is avalible, set NewData event.
					SetEvent(Comm->NewData);

					WaitForSingleObject(Comm->CommDone, INFINITE);

					//Display the data that has been recieved.
					ResetEvent(Comm->CommDone);
					ui.CommView->append( "Gun centert" );
					QCoreApplication::processEvents();
				};

				ui.RXLed->setProperty("value", QVariant(true));
				QCoreApplication::processEvents();
				ui.RXLed->setProperty("value", QVariant(false));
				QCoreApplication::processEvents();

				cvWaitKey(1);
				QCoreApplication::processEvents();
			}
			else if(ui.radioThreshold->isChecked()){
				ui.DataView->setText("Showing threshold image");
				if(ui.radioBlue->isChecked()){
					blob.LoadLiveFeed(Cam,1);
				}
				else if(ui.radioYellow->isChecked()){
					blob.LoadLiveFeed(Cam,2);
				}
				else if(ui.radioGreen->isChecked()){
					blob.LoadLiveFeed(Cam,3);
				}
				else if(ui.radioRed->isChecked()){
					blob.LoadLiveFeed(Cam,4);
				}
				else{
					blob.LoadLiveFeed(Cam,0);
				};
				blob.Image_Scan();

				qimage = QImage(blob.WorkImage.data, blob.WorkImage.cols, blob.WorkImage.rows, blob.WorkImage.cols, QImage::Format_Indexed8);
				pixmap = QPixmap::fromImage(qimage);
				ui.ImageView->setPixmap(pixmap); 
				ui.ImageView->adjustSize();


				ui.TXLed->setProperty("value", QVariant(true));
				QCoreApplication::processEvents();
				ui.TXLed->setProperty("value", QVariant(false));
				QCoreApplication::processEvents();

				//Check X
				if((blob.LastMassCol) < ((blob.WorkImage.cols / 2) - 10)){
					X++;
					Comm->X = X;
					ui.CommView->append( "left" );
				}else if((blob.LastMassCol) > ((blob.WorkImage.cols / 2) + 10)) {

					X--;
					Comm->X = X;
					ui.CommView->append( "right" );
				}else{
					ui.CommView->append( "On target" );
				};

				//Check Y
				if((blob.LastMassRow) < ((blob.WorkImage.rows / 2) + 10)){
					Y++;
					Comm->Y = Y;
					ui.CommView->append( "down" );
				}else if((blob.LastMassRow) > ((blob.WorkImage.rows / 2) - 10)){
					Y--;
					Comm->Y = Y;
					ui.CommView->append( "up" );
				};

				//New data is avalible, set NewData event.
				SetEvent(Comm->NewData);

				WaitForSingleObject(Comm->CommDone, INFINITE);

				blob.LastTransX = blob.LastMassCol;
				blob.LastTransY = blob.LastMassRow;
				ResetEvent(Comm->CommDone);

				//if (((Y-1) == -1) || ((Y+1) == 180) || ((X-1) == -1) || ((X+1) == 180)){
				if ((X == 0) || (X == 180)){
					ui.CommView->append( "Target out of range, centering gun" );
					QCoreApplication::processEvents();
					Y = 90;
					X = 90;

					//Center gun.
					Comm->X = X;
					Comm->Y = Y;

					//New data is avalible, set NewData event.
					SetEvent(Comm->NewData);

					WaitForSingleObject(Comm->CommDone, INFINITE);

					//Display the data that has been recieved.
					ResetEvent(Comm->CommDone);
					ui.CommView->append( "Gun centert" );
					QCoreApplication::processEvents();
				};

				ui.RXLed->setProperty("value", QVariant(true));
				QCoreApplication::processEvents();
				ui.RXLed->setProperty("value", QVariant(false));
				QCoreApplication::processEvents();

				cvWaitKey(1);
				QCoreApplication::processEvents();
			}else{
				ui.DataView->setText("No image type loaded");
				cvWaitKey(1);
				QCoreApplication::processEvents();
			};
			cvWaitKey(1);
			QCoreApplication::processEvents();
		};
	}
	else{
		ui.LogView->append("[" + Time.currentDateTime().toString ("hh:mm:ss.zzz") + "] " + "Cannot execute dynamic tracking mode, uplink not establisched");
	};
};

void Sentry::QuitMode(){
	QCoreApplication::processEvents();
	AutoOn = false;
	ManualOn = false;
	ui.LogView->append("[" + Time.currentDateTime().toString ("hh:mm:ss.zzz") + "] " + "Quiting application...");
	QCoreApplication::processEvents();
	thread->quit();
	//Give the thread time to quit
	Sleep(2000);
	Comm->~Communicator();
	Cam.~VideoCapture();
	ui.LogView->append("[" + Time.currentDateTime().toString ("hh:mm:ss.zzz") + "] " + "Closed com port and camera");
	ui.ImageView->setPixmap(QPixmap("logo.jpg"));
	QCoreApplication::processEvents();
	QCoreApplication::quit();
};

void Sentry::Connect(){
	QCoreApplication::processEvents();
	thread->start();

	//Empty list so that there are no duplications.
	ui.ComComboBox->clear();

	//Com port data structure for storing detected com port
	COMMCONFIG ccfg;

	//Search for com ports, if a comport is found then store it as an item in the combobox.
	//The item is an device id that is used in the setup function to setup an connection. 
	for (int i = 0; i < 20; i++)
	{
		std::ostringstream oss;
		oss << "COM" << i;
		ccfg.dwSize = sizeof COMMCONFIG;
		DWORD siz = sizeof COMMCONFIG;
		std::string comstring = oss.str();
		BOOL res = GetDefaultCommConfigA (comstring.c_str(), &ccfg, &siz);
		if (res){
			ui.ComComboBox->addItem("COM" + QString::number(i));
		};
	};

	CurrentCom = ui.ComComboBox->currentText();
	ui.LogView->append("[" + Time.currentDateTime().toString ("hh:mm:ss.zzz") + "] " + CurrentCom);


	if(Comm->Setup(CurrentCom) == 0){
		ui.UpLinkLed->setProperty("value", QVariant(true));
		ui.LogView->append("[" + Time.currentDateTime().toString ("hh:mm:ss.zzz") + "] " + "Uplink established");
		QCoreApplication::processEvents();
		UpLink = true;
	}
	else{
		ui.UpLinkLed->setProperty("value", QVariant(false));
		ui.LogView->append("[" + Time.currentDateTime().toString ("hh:mm:ss.zzz") + "] " + "Uplink failed");
		QCoreApplication::processEvents();
		UpLink = false;
	};


	ui.ImageView->setPixmap(QPixmap("logo.jpg"));
	QCoreApplication::processEvents();
	ui.LogView->append("[" + Time.currentDateTime().toString ("hh:mm:ss.zzz") + "] " + "Connected");
	ui.ConnectButton->setEnabled(false);
	ui.DisconnectButton->setEnabled(true);
	ui.GetImageButton->setEnabled(true);
	ui.AutoButton->setEnabled(true);
	ui.ManualButton->setEnabled(true);
	ui.AutoDynamicButton->setEnabled(true);
	QCoreApplication::processEvents();
};

void Sentry::Disconnect(){
	QCoreApplication::processEvents();
	AutoOn = false;
	ManualOn = false;
	thread->quit();
	//Give the thread time to quit
	Sleep(2000);

	//Close connection. Try this if not catch.
	try {
		Comm->port->close();
		ui.UpLinkLed->setProperty("value", QVariant(false));
	UpLink = false;
	ui.ImageView->setPixmap(QPixmap("logo.jpg")); 
	ui.LogView->append("[" + Time.currentDateTime().toString ("hh:mm:ss.zzz") + "] " + "Disconected");
	ui.AutoLed->setProperty("value", QVariant(false));
	ui.ConnectButton->setEnabled(true);
	ui.DisconnectButton->setEnabled(false);
	ui.GetImageButton->setEnabled(false);
	ui.UpButton->setEnabled(false);
	ui.RightButton->setEnabled(false);
	ui.DownButton->setEnabled(false);
	ui.LeftButton->setEnabled(false);
	ui.FireButton->setEnabled(false);
	ui.AutoButton->setEnabled(false);
	ui.ManualButton->setEnabled(false);
	ui.AutoDynamicButton->setEnabled(false);
	QCoreApplication::processEvents();
	} catch( boost::system::system_error ) {}

};

void Sentry::Manual(){
	if(UpLink){
		ui.OfflineLed->setProperty("value", QVariant(false));
		ui.AutoLed->setProperty("value", QVariant(false));
		ui.AutoDynamicButton->setEnabled(true);
		ui.InitLed->setProperty("value", QVariant(true));
		ui.ManualButton->setEnabled(false);
		ui.AutoButton->setEnabled(true);
		QCoreApplication::processEvents();
		AutoOn = false;
		ManualOn = true;
		ui.ImageView->setPixmap(QPixmap("logo.jpg")); 
		ui.LogView->append("[" + Time.currentDateTime().toString ("hh:mm:ss.zzz") + "] " + "Manual mode activated");
		ui.AutoLed->setProperty("value", QVariant(false));
		ui.ConnectButton->setEnabled(false);
		ui.DisconnectButton->setEnabled(true);
		QCoreApplication::processEvents();
		thread->start();
		Sleep(5000);
		ui.InitLed->setProperty("value", QVariant(false));
		ui.ManualLed->setProperty("value", QVariant(true));
		ui.UpButton->setEnabled(true);
		ui.RightButton->setEnabled(true);
		ui.DownButton->setEnabled(true);
		ui.LeftButton->setEnabled(true);
		ui.FireButton->setEnabled(true);
		QCoreApplication::processEvents();

		//Center gun.
		Comm->X = Xas;
		Comm->Y = Yas;
		Comm->Fire = 0;

		//New data is avalible, set NewData event.
		SetEvent(Comm->NewData);

		WaitForSingleObject(Comm->CommDone, INFINITE);

		//Display the data that has been recieved.
		ResetEvent(Comm->CommDone);
		QCoreApplication::processEvents();

		while(ManualOn){
			while((!UpPressed)||(!DownPressed)||(!RightPressed)||(!LeftPressed)||(!FirePressed)){

				//Get image and display else button function is called
				blob.Crosshair(Cam);
				cvtColor(blob.Image, blob.QTImage, CV_BGR2RGB);
				qimage = QImage(blob.QTImage.data, blob.QTImage.cols, blob.QTImage.rows, blob.QTImage.cols*3, QImage::Format_RGB888);
				pixmap = QPixmap::fromImage(qimage);
				ui.ImageView->setPixmap(pixmap); 
				ui.ImageView->adjustSize();
				QCoreApplication::processEvents();

				if(!ManualOn){
					break;
				};
			};

			QCoreApplication::processEvents();
		};
		QCoreApplication::processEvents();
	}
	else{
		ui.LogView->append("[" + Time.currentDateTime().toString ("hh:mm:ss.zzz") + "] " + "Cannot execute manuel mode, uplink not establisched");
	};
};


void Sentry::Up(){

	UpPressed = true;
	while(UpPressed){
		Yas--;
		Comm->X = Xas;
		Comm->Y = Yas;

		//Transmit and recieve data
		SetEvent(Comm->NewData);
		WaitForSingleObject(Comm->CommDone, INFINITE);
		ResetEvent(Comm->CommDone);
		ui.CommView->append( "Up");
		ui.CommView->append( "X value com: " + QString::number(Comm->X) );
		ui.CommView->append( "Y value com: " + QString::number(Comm->Y) );
		blob.Crosshair(Cam);
		cvtColor(blob.Image, blob.QTImage, CV_BGR2RGB);
		qimage = QImage(blob.QTImage.data, blob.QTImage.cols, blob.QTImage.rows, blob.QTImage.cols*3, QImage::Format_RGB888);
		pixmap = QPixmap::fromImage(qimage);
		ui.ImageView->setPixmap(pixmap); 
		ui.ImageView->adjustSize();
		QCoreApplication::processEvents();

		if((Yas-1) == -1){
			Yas = 90;
		};
	};
	UpPressed = false;
};

void Sentry::Right(){

	RightPressed = true;
	while(RightPressed){
		Xas--;
		Comm->X = Xas;
		Comm->Y = Yas;

		//Transmit and recieve data
		SetEvent(Comm->NewData);
		WaitForSingleObject(Comm->CommDone, INFINITE);
		ResetEvent(Comm->CommDone);
		ui.CommView->append( "Right");
		ui.CommView->append( "X value com: " + QString::number(Comm->X) );
		ui.CommView->append( "Y value com: " + QString::number(Comm->Y) );
		blob.Crosshair(Cam);
		cvtColor(blob.Image, blob.QTImage, CV_BGR2RGB);
		qimage = QImage(blob.QTImage.data, blob.QTImage.cols, blob.QTImage.rows, blob.QTImage.cols*3, QImage::Format_RGB888);
		pixmap = QPixmap::fromImage(qimage);
		ui.ImageView->setPixmap(pixmap); 
		ui.ImageView->adjustSize();
		QCoreApplication::processEvents();

		if((Xas-1) == -1){
			Xas = 90;
		};
	};
	RightPressed = false;
};

void Sentry::Down(){

	DownPressed = true;
	while(DownPressed){
		Yas++;
		Comm->X = Xas;
		Comm->Y = Yas;

		//Transmit and recieve data
		SetEvent(Comm->NewData);
		WaitForSingleObject(Comm->CommDone, INFINITE);
		ResetEvent(Comm->CommDone);
		ui.CommView->append( "Down");
		ui.CommView->append( "X value com: " + QString::number(Comm->X) );
		ui.CommView->append( "Y value com: " + QString::number(Comm->Y) );
		blob.Crosshair(Cam);
		cvtColor(blob.Image, blob.QTImage, CV_BGR2RGB);
		qimage = QImage(blob.QTImage.data, blob.QTImage.cols, blob.QTImage.rows, blob.QTImage.cols*3, QImage::Format_RGB888);
		pixmap = QPixmap::fromImage(qimage);
		ui.ImageView->setPixmap(pixmap); 
		ui.ImageView->adjustSize();
		QCoreApplication::processEvents();

		if((Yas+1) == 181){
			Yas = 90;
		};
	};
	DownPressed = false;
};

void Sentry::Left(){

	LeftPressed = true;
	while(LeftPressed){
		Xas++;
		Comm->X = Xas;
		Comm->Y = Yas;

		//Transmit and recieve data
		SetEvent(Comm->NewData);
		WaitForSingleObject(Comm->CommDone, INFINITE);
		ResetEvent(Comm->CommDone);
		ui.CommView->append( "Left");
		ui.CommView->append( "X value com: " + QString::number(Comm->X) );
		ui.CommView->append( "Y value com: " + QString::number(Comm->Y) );

		ui.LogView->append("[" + Time.QDateTime::toString ("hh:mm:ss.zzz") + "] " + "Test");

		blob.Crosshair(Cam);
		cvtColor(blob.Image, blob.QTImage, CV_BGR2RGB);
		qimage = QImage(blob.QTImage.data, blob.QTImage.cols, blob.QTImage.rows, blob.QTImage.cols*3, QImage::Format_RGB888);
		pixmap = QPixmap::fromImage(qimage);
		ui.ImageView->setPixmap(pixmap); 
		ui.ImageView->adjustSize();
		QCoreApplication::processEvents();

		if((Xas+1) == 181){
			Xas = 90;
		};
	};
	LeftPressed = false;
};

void Sentry::Fire(){

	FirePressed = true;
	while(FirePressed){

		FireText = ui.FireTextBox->toPlainText();
		Comm->Fire = FireText.toInt(); 
		//Transmit and recieve data
		SetEvent(Comm->NewData);
		WaitForSingleObject(Comm->CommDone, INFINITE);
		ResetEvent(Comm->CommDone);
		ui.CommView->append( "Fire" );
		ui.CommView->append( "Fire value: " + QString::number(Comm->Fire) );

		blob.Crosshair(Cam);
		cvtColor(blob.Image, blob.QTImage, CV_BGR2RGB);
		qimage = QImage(blob.QTImage.data, blob.QTImage.cols, blob.QTImage.rows, blob.QTImage.cols*3, QImage::Format_RGB888);
		pixmap = QPixmap::fromImage(qimage);
		ui.ImageView->setPixmap(pixmap); 
		ui.ImageView->adjustSize();
		QCoreApplication::processEvents();
	};
	FirePressed = false;
};

void Sentry::SetButton(){

	UpPressed = false;
	RightPressed = false;
	DownPressed = false;
	LeftPressed = false;
	FirePressed = false;

};

void Sentry::SetHueLow(int i)
{
	//change hue value for the lower end
	if (ui.radioBlue->isChecked())
	{
		blob.Blue.HLower = i;
		ui.HueLowVal->append(QString::number(blob.Blue.HLower));
	}
	if (ui.radioYellow->isChecked())
	{
		blob.Yellow.HLower = i;
		ui.HueLowVal->append(QString::number(blob.Yellow.HLower));
	}
	if (ui.radioGreen->isChecked())
	{
		blob.Green.HLower = i;
		ui.HueLowVal->append(QString::number(blob.Green.HLower));
	}
	if (ui.radioRed->isChecked())
	{
		blob.Red.HLower = i;
		ui.HueLowVal->append(QString::number(blob.Red.HLower));
	}
}

void Sentry::SetSatLow(int i)
{
	//change saturation value for the lower end
	if (ui.radioBlue->isChecked())
	{
		blob.Blue.SLower = i;
		ui.SatLowVal->append(QString::number(blob.Blue.SLower));
	}
	if (ui.radioYellow->isChecked())
	{
		blob.Yellow.SLower = i;
		ui.SatLowVal->append(QString::number(blob.Yellow.SLower));
	}
	if (ui.radioGreen->isChecked())
	{
		blob.Green.SLower = i;
		ui.SatLowVal->append(QString::number(blob.Green.SLower));
	}
	if (ui.radioRed->isChecked())
	{
		blob.Red.SLower = i;
		ui.SatLowVal->append(QString::number(blob.Red.SLower));
	}
}

void Sentry::SetValLow(int i)
{
	//change VALUE value for the lower end
	if (ui.radioBlue->isChecked())
	{
		blob.Blue.VLower = i;
		ui.ValLowVal->append(QString::number(blob.Blue.VLower));
	}
	if (ui.radioYellow->isChecked())
	{
		blob.Yellow.VLower = i;
		ui.ValLowVal->append(QString::number(blob.Yellow.VLower));
	}
	if (ui.radioGreen->isChecked())
	{
		blob.Green.VLower = i;
		ui.ValLowVal->append(QString::number(blob.Green.VLower));
	}
	if (ui.radioRed->isChecked())
	{
		blob.Red.VLower = i;
		ui.ValLowVal->append(QString::number(blob.Red.VLower));
	}
}

//functions to set the high values
void Sentry::SetHueHigh(int i)
{
	//change hue value for the higher end
	if (ui.radioBlue->isChecked())
	{
		blob.Blue.HUpper = i;
		ui.HueHighVal->append(QString::number(blob.Blue.HUpper));
	}
	if (ui.radioYellow->isChecked())
	{
		blob.Yellow.HUpper = i;
		ui.HueHighVal->append(QString::number(blob.Yellow.HUpper));
	}
	if (ui.radioGreen->isChecked())
	{
		blob.Green.HUpper = i;
		ui.HueHighVal->append(QString::number(blob.Green.HUpper));
	}
	if (ui.radioRed->isChecked())
	{
		blob.Red.HUpper = i;
		ui.HueHighVal->append(QString::number(blob.Red.HUpper));
	}
}

void Sentry::SetSatHigh(int i)
{
	//change saturation value for the higher end
	if (ui.radioBlue->isChecked())
	{
		blob.Blue.SUpper = i;
		ui.SatHighVal->append(QString::number(blob.Blue.SUpper));
	}
	if (ui.radioYellow->isChecked())
	{
		blob.Yellow.SUpper = i;
		ui.SatHighVal->append(QString::number(blob.Yellow.SUpper));
	}
	if (ui.radioGreen->isChecked())
	{
		blob.Green.SUpper = i;
		ui.SatHighVal->append(QString::number(blob.Green.SUpper));
	}
	if (ui.radioRed->isChecked())
	{
		blob.Red.SUpper = i;
		ui.SatHighVal->append(QString::number(blob.Red.SUpper));
	}
}

void Sentry::SetValHigh(int i)
{
	//change VALUE value for the higher end
	if (ui.radioBlue->isChecked())
	{
		blob.Blue.VUpper = i;
		ui.ValHighVal->append(QString::number(blob.Blue.VUpper));
	}
	if (ui.radioYellow->isChecked())
	{
		blob.Yellow.VUpper = i;
		ui.ValHighVal->append(QString::number(blob.Yellow.VUpper));
	}
	if (ui.radioGreen->isChecked())
	{
		blob.Green.VUpper = i;
		ui.ValHighVal->append(QString::number(blob.Green.VUpper));
	}
	if (ui.radioRed->isChecked())
	{
		blob.Red.VUpper = i;
		ui.ValHighVal->append(QString::number(blob.Red.VUpper));
	}
}

void Sentry::ResetLowVals()
{
	if (ui.radioBlue->isChecked())
	{
		blob.Blue.HLower = 85;
		blob.Blue.SLower = 100;
		blob.Blue.VLower = 100;
		ui.HueLowVal->append(QString::number(blob.Blue.HLower));
		ui.SatLowVal->append(QString::number(blob.Blue.SLower));
		ui.ValLowVal->append(QString::number(blob.Blue.VLower));
		ui.HueLow->setValue(blob.Blue.HLower);
		ui.SatLow->setValue(blob.Blue.SLower);
		ui.ValLow->setValue(blob.Blue.VLower);
	}
	if (ui.radioYellow->isChecked())
	{
		blob.Yellow.HLower = 24;
		blob.Yellow.SLower = 200;
		blob.Yellow.VLower = 200;
		ui.HueLowVal->append(QString::number(blob.Yellow.HLower));
		ui.SatLowVal->append(QString::number(blob.Yellow.SLower));
		ui.ValLowVal->append(QString::number(blob.Yellow.VLower));
		ui.HueLow->setValue(blob.Yellow.HLower);
		ui.SatLow->setValue(blob.Yellow.SLower);
		ui.ValLow->setValue(blob.Yellow.VLower);
	}
	if (ui.radioGreen->isChecked())
	{
		blob.Green.HLower = 35;
		blob.Green.SLower = 100;
		blob.Green.VLower = 100;
		ui.HueLowVal->append(QString::number(blob.Green.HLower));
		ui.SatLowVal->append(QString::number(blob.Green.SLower));
		ui.ValLowVal->append(QString::number(blob.Green.VLower));
		ui.HueLow->setValue(blob.Green.HLower);
		ui.SatLow->setValue(blob.Green.SLower);
		ui.ValLow->setValue(blob.Green.VLower);
	}
	if (ui.radioRed->isChecked())
	{
		blob.Red.HLower = 175;
		blob.Red.SLower = 200;
		blob.Red.VLower = 170;
		ui.HueLowVal->append(QString::number(blob.Red.HLower));
		ui.SatLowVal->append(QString::number(blob.Red.SLower));
		ui.ValLowVal->append(QString::number(blob.Red.VLower));
		ui.HueLow->setValue(blob.Red.HLower);
		ui.SatLow->setValue(blob.Red.SLower);
		ui.ValLow->setValue(blob.Red.VLower);
	}
}

void Sentry::ResetHighVals()
{
	if (ui.radioBlue->isChecked())
	{
		blob.Blue.HUpper = 130;
		blob.Blue.SUpper = 255;
		blob.Blue.VUpper = 255;
		ui.HueHighVal->append(QString::number(blob.Blue.HUpper));
		ui.SatHighVal->append(QString::number(blob.Blue.SUpper));
		ui.ValHighVal->append(QString::number(blob.Blue.VUpper));
		ui.HueHigh->setValue(blob.Blue.HUpper);
		ui.SatHigh->setValue(blob.Blue.SUpper);
		ui.ValHigh->setValue(blob.Blue.VUpper);
	}
	if (ui.radioYellow->isChecked())
	{
		blob.Yellow.HUpper = 32;
		blob.Yellow.SUpper = 255;
		blob.Yellow.VUpper = 255;
		ui.HueHighVal->append(QString::number(blob.Yellow.HUpper));
		ui.SatHighVal->append(QString::number(blob.Yellow.SUpper));
		ui.ValHighVal->append(QString::number(blob.Yellow.VUpper));
		ui.HueHigh->setValue(blob.Yellow.HUpper);
		ui.SatHigh->setValue(blob.Yellow.SUpper);
		ui.ValHigh->setValue(blob.Yellow.VUpper);
	}
	if (ui.radioGreen->isChecked())
	{
		blob.Green.HUpper = 80;
		blob.Green.SUpper = 255;
		blob.Green.VUpper = 255;
		ui.HueHighVal->append(QString::number(blob.Green.HUpper));
		ui.SatHighVal->append(QString::number(blob.Green.SUpper));
		ui.ValHighVal->append(QString::number(blob.Green.VUpper));
		ui.HueHigh->setValue(blob.Green.HUpper);
		ui.SatHigh->setValue(blob.Green.SUpper);
		ui.ValHigh->setValue(blob.Green.VUpper);
	}
	if (ui.radioRed->isChecked())
	{
		blob.Red.HUpper = 179;
		blob.Red.SUpper = 255;
		blob.Red.VUpper = 255;
		ui.HueHighVal->append(QString::number(blob.Red.HUpper));
		ui.SatHighVal->append(QString::number(blob.Red.SUpper));
		ui.ValHighVal->append(QString::number(blob.Red.VUpper));
		ui.HueHigh->setValue(blob.Red.HUpper);
		ui.SatHigh->setValue(blob.Red.SUpper);
		ui.ValHigh->setValue(blob.Red.VUpper);
	}
}

void Sentry::Beweging_detector_caller()
{
	ui.LogView->append("[" + Time.currentDateTime().toString ("hh:mm:ss.zzz") + "] " + "Motion detection activated");
	QCoreApplication::processEvents();
	beweging_detector();
}

void Sentry::Calibrate(){
	ui.LogView->append("[" + Time.currentDateTime().toString ("hh:mm:ss.zzz") + "] " + "Calibration mode activated");
	QCoreApplication::processEvents();
	ui.HueLow->setEnabled(true);
	ui.HueHigh->setEnabled(true);
	ui.SatLow->setEnabled(true);
	ui.SatHigh->setEnabled(true);
	ui.ValLow->setEnabled(true);
	ui.ValHigh->setEnabled(true);
	ui.ResetHighButton->setEnabled(true);
	ui.ResetLowButton->setEnabled(true);
	ui.LockLowerButton->setEnabled(true);
	ui.LockHigherButton->setEnabled(true);
};

void Sentry::LockLowerVals(){
	ui.HueLow->setEnabled(false);
	ui.SatLow->setEnabled(false);
	ui.ValLow->setEnabled(false);
	ui.ResetLowButton->setEnabled(false);
	ui.LockLowerButton->setEnabled(false);
}

void Sentry::LockHigherVals(){
	ui.HueHigh->setEnabled(false);
	ui.SatHigh->setEnabled(false);
	ui.ValHigh->setEnabled(false);
	ui.ResetHighButton->setEnabled(false);
	ui.LockHigherButton->setEnabled(false);
}

void Sentry::ClearLog(){
	ui.LogView->clear();
};

void Sentry::SaveLog(){

	//Create dialog window
	QString DialogString = QFileDialog::getSaveFileName(this, tr("Save Logfile"),
		//Default save filename
		"Senty log",
		//Save format option that may be selected
		tr("Text Files (*.txt)"));

	//Check if DialogString that is returned is not empty and therefore the dialog is created succesfully.
	if (DialogString != "") {
		//Create logfile.
		QFile file(DialogString);
		//Check if the created file is opened and in the right modus(Write only).
		if (!file.open(QIODevice::WriteOnly)) {
			ui.LogView->append("[" + Time.currentDateTime().toString ("hh:mm:ss.zzz") + "] " + "Failed to save log to file");
		} else {
			//Create text stream (that writes to the file), converd log data to plain text and write te stream. 
			QTextStream stream(&file);
			stream << ui.LogView->toPlainText();

			//Flush stream clean so no bogus data is still on the stream and close file.
			stream.flush();
			file.close();
		}
	}
};

void Sentry::LoadLog(){

	//Create dialog window
	QString DialogString = QFileDialog::getOpenFileName(this, tr("Save Logfile"),
		//Default load filename
		"Senty log",
		//Load format option that may be selected
		tr("Text Files (*.txt)"));

	//Check if DialogString that is returned is not empty and therefore the dialog is created succesfully.
	if (DialogString != "") {
		//Create logfile.
		QFile file(DialogString);
		//Check if the created file is opened and in the right modus(Read only).
		if (!file.open(QIODevice::ReadOnly)) {
			ui.LogView->append("[" + Time.currentDateTime().toString ("hh:mm:ss.zzz") + "] " + "Failed to load log to file");
		} else {
			//Create text stream (that writes to the file), converd log data to plain text and write te stream. 
			QTextStream stream(&file);
			ui.LogView->setText(stream.readAll());

			//Close file.
			file.close();
		}
	}
};

//Function to update the current com variable. 
//This function is called when the combobox is clicked and sets the current combobox index item current com variable.
void Sentry::UpdateCom(){

	if(!UpLink){
		ui.LogView->append("[" + Time.currentDateTime().toString ("hh:mm:ss.zzz") + "] " + "Combox changed");
		CurrentCom = ui.ComComboBox->itemText(ui.ComComboBox->currentIndex());
		ui.LogView->append("[" + Time.currentDateTime().toString ("hh:mm:ss.zzz") + "] " + CurrentCom);
		QCoreApplication::processEvents();
	}
	else{
		ui.LogView->append("[" + Time.currentDateTime().toString ("hh:mm:ss.zzz") + "] " + "Uplink is establisched, can't change current com value");
		QCoreApplication::processEvents();
	};
};